package com.inspur.jzsxxzx.controller.muluzhili;

import com.inspur.jzsxxzx.entity.muluzhili.UpDataCatalog;
import com.inspur.jzsxxzx.entity.muluzhili.UpDataCatalogItem;
import com.inspur.jzsxxzx.entity.muluzhili.UpDataReconciliation;
import com.inspur.jzsxxzx.entity.primary.CataUploadInfo;
import com.inspur.jzsxxzx.service.catalog.MuluzhiliVOService;
import com.inspur.jzsxxzx.service.catalog.MuluzhiliItemVOService;
import com.inspur.jzsxxzx.service.primary.CataUploadInfoService;
import com.inspur.jzsxxzx.service.muluzhili.UpDataCatalogItemService;
import com.inspur.jzsxxzx.service.muluzhili.UpDataCatalogService;
import com.inspur.jzsxxzx.service.muluzhili.UpDataReconciliationService;
import com.inspur.jzsxxzx.util.DateUtils;
import com.inspur.jzsxxzx.vo.MuluzhiliVO;

import com.inspur.jzsxxzx.vo.MuluzhiliItemVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/muluzhili")
public class MuluzhiliVOController {

    @Value("${muluzhili.process-level}")
    String process_level;

    @Value("${muluzhili.other-update-cycle}")
    String other_update_cycle;

    @Value("${region-code}")
    String region_code;

    @Autowired
    private MuluzhiliVOService muluzhiliVOService;

    @Autowired
    private MuluzhiliItemVOService muluzhiliItemVOService;

    @Autowired
    private UpDataCatalogService upDataCatalogService;

    @Autowired
    private UpDataCatalogItemService upDataCatalogItemService;

    @Autowired
    private CataUploadInfoService cataUploadInfoService;

    @Autowired
    private UpDataReconciliationService upDataReconciliationService;

    /**
     * 获取目录治理VO数据，支持分页和条件查询
     *
     * @param page            页码，默认为1
     * @param limit           每页条数，默认为10
     * @param cataTitle       目录标题（模糊查询）
     * @param internalOrgName 政务数据提供方名称（模糊查询）
     * @return 分页数据结果
     */
    @GetMapping("/data")
    public Map<String, Object> getMuluzhiliData(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int limit,
            @RequestParam(required = false) String cataTitle,
            @RequestParam(required = false) String internalOrgName) {

        Map<String, Object> result = new HashMap<>();

        try {
            MuluzhiliVO condition = new MuluzhiliVO();
            if (cataTitle != null && !cataTitle.isEmpty()) {
                condition.setCataTitle(cataTitle);
            }
            if (internalOrgName != null && !internalOrgName.isEmpty()) {
                condition.setInternalOrgName(internalOrgName);
            }

            int totalCount = muluzhiliVOService.countByCondition(condition);

            List<MuluzhiliVO> pageData = muluzhiliVOService.findByPage(condition, page, limit);

            result.put("code", 0);
            result.put("count", totalCount);
            result.put("data", pageData);
        } catch (Exception e) {
            e.printStackTrace();
            result.put("code", 1);
            result.put("msg", "数据加载失败: " + e.getMessage());
        }

        return result;
    }

    /**
     * 上报所有认领目录数据到目录治理数据库
     *
     * @return 上报结果
     */
    @PostMapping("/uploadAllCatalogData")
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> uploadAllCatalogData() {
        Map<String, Object> result = new HashMap<>();

        int number = 0;
        int columnNumber = 0;
        try {

            // 目录相关逻辑（包括上报到省数据库及本地数据标记）
            List<MuluzhiliVO> allData = muluzhiliVOService.findAll();
            Map<String, Integer> map = uploadCatalog(allData);

            number = map.get("number");
            columnNumber = map.get("columnNumber");

            result.put("code", 0);
            result.put("msg", "成功上传 " + number + " 条目录，" + columnNumber + " 条信息项");
        } catch (Exception e) {
            e.printStackTrace();
            result.put("code", 1);
            result.put("msg", "数据上传失败: " + e.getMessage());
            throw new RuntimeException(e);
        }

        return result;
    }

    /**
     * 按部门代码上报认领目录数据到目录治理数据库
     *
     * @param deptCode 部门代码（分类码的第3-4位）
     * @return 上报结果
     */
    @PostMapping("/uploadCatalogByDept")
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> uploadCatalogByDept(@RequestParam String deptCode) {
        Map<String, Object> result = new HashMap<>();

        int number = 0;
        int columnNumber = 0;
        try {
            // 根据部门代码筛选目录数据
            List<MuluzhiliVO> deptData = muluzhiliVOService.findByDeptCode(deptCode);

            Map<String, Integer> map = uploadCatalog(deptData);

            number = map.get("number");
            columnNumber = map.get("columnNumber");
            result.put("code", 0);
            result.put("msg", "成功上传 " + number + " 条目录，" + columnNumber + " 条信息项");
        } catch (Exception e) {
            e.printStackTrace();
            result.put("code", 1);
            result.put("msg", "数据上传失败: " + e.getMessage());
            throw new RuntimeException(e);
        }

        return result;
    }

    @Transactional(rollbackFor = Exception.class)
    public Map<String, Integer> uploadCatalog(List<MuluzhiliVO> list) {
        Map<String, Integer> result = new HashMap<>();
        // 目录数量
        int number = 0;
        // 信息项数量
        int columnNumber = 0;
        // 系统编号
        int system_id = 1;

        Map<String, String> sysMap = new HashMap<>();

        // 生成批次号
        int cd_num = 1;
        String cdBatch = DateUtils.generateCdBatch(cd_num);

        if (list != null && list.size() > 0) {
            int maxId = upDataCatalogService.findMaxId() == null ? 1 : upDataCatalogService.findMaxId() + 1;
            number = list.size();

            for (MuluzhiliVO mv : list) {
                String extCataId = UUID.randomUUID().toString();
                String cataBasicId = mv.getCataBasicId();
                String regionCode = mv.getRegionCode();
                String version = mv.getExtCataVersion();

                String updateCycle = mv.getUpdateCycle();
                String otherUpdateCycle = mv.getOtherUpdateCycle();
                if ("8".equals(updateCycle) && (otherUpdateCycle == null || otherUpdateCycle.trim().isEmpty())) {
                    otherUpdateCycle = other_update_cycle;
                }

                String pocessLevel = mv.getProcessLevel();
                if (pocessLevel == null || pocessLevel.trim().isEmpty()) {
                    pocessLevel = process_level;
                }

                String sourceItemName = mv.getSourceItemName();
                if("null".equals(sourceItemName.trim())){
                    sourceItemName = null;
                }
                String sourceItemCode = mv.getSourceItemCode();
                if("null".equals(sourceItemCode.trim())){ 
                    sourceItemCode = null;
                }
                String taskCatalogName = mv.getTaskCatalogName();
                if("null".equals(taskCatalogName.trim())){ 
                    taskCatalogName = null;
                }
                String taskCatalogCode = mv.getTaskCatalogCode();
                if("null".equals(taskCatalogCode.trim())){ 
                    taskCatalogCode = null;
                }

                UpDataCatalog udc = new UpDataCatalog();
                udc.setId(maxId++);
                udc.setBaseCataId(cataBasicId);
                udc.setExtCataId(extCataId);
                udc.setExtCataTitle(mv.getCataTitle());
                udc.setBusinessGroupName(mv.getBusinessGroupName());
                udc.setExtCataCode(mv.getCategoryCode());
                udc.setFieldType(mv.getFieldType());
                udc.setFieldTypeName(mv.getFieldTypeName());
                udc.setTaskCatalogName(taskCatalogName);
                udc.setTaskCatalogCode(taskCatalogCode);
                udc.setUseLevel(mv.getUserLevel());
                udc.setDescription(mv.getDescription());
                udc.setExtDataCataCode(mv.getExtDataCataCode());
                udc.setSharedCondition(mv.getSharedCondition());
                udc.setSourceItemName(sourceItemName);
                udc.setSourceItemCode(sourceItemCode);
                udc.setRelationItemName(mv.getRelationItemName());
                udc.setRelationItemCode(mv.getRelationItemCode());
                udc.setImportanceLevel(mv.getImportanceLevel());
                udc.setPocessLevel(pocessLevel);
                udc.setAeraScope(mv.getAreaScope());
                udc.setOtherAeraScope("");
                udc.setTimeRange(mv.getTimeRange() == null ? "无" : mv.getTimeRange());
                udc.setInternalOrgName(mv.getInternalOrgName());
                udc.setOrgCode(mv.getOrgCode());
                udc.setExtDescription(mv.getExtDescription());
                udc.setUpdateCycle(updateCycle);
                udc.setOtherUpdateCycle(otherUpdateCycle);
                udc.setIsPublish(mv.getIsPublish());
                udc.setNotPublishReason(mv.getNotPublishReason());
                udc.setRegionName(mv.getRegionName());
                udc.setRegionCode(regionCode);
                udc.setCatalogType(mv.getCatalogType());
                udc.setExtCataVersion(version);
                udc.setStatus(mv.getStatus());
                udc.setCreateTime(new Date());
                udc.setUpdateTime(new Date());
                udc.setCdTime(new Date());
                udc.setCdBatch(cdBatch);

                upDataCatalogService.save(udc);

                int versionNum = version.contains(".") ? Integer.parseInt(version.substring(0, version.indexOf(".")))
                        : Integer.parseInt(version);
                // 给上传的目录做标记
                CataUploadInfo cui = new CataUploadInfo();
                cui.setCataId(mv.getCataId());
                cui.setCataBasicId(cataBasicId);
                cui.setExtCataId(extCataId);
                cui.setVersion(versionNum);
                cui.setStatus(1);
                cui.setCreateTime(new Date());
                cui.setUpdateTime(new Date());

                cataUploadInfoService.save(cui);

                // 目录信息项相关逻辑
                List<MuluzhiliItemVO> itemList = muluzhiliItemVOService.getByCataBasicIdAndVersion(cataBasicId,
                        versionNum);
                if (itemList != null && itemList.size() > 0) {
                    columnNumber += itemList.size();
                    int columnMaxId = upDataCatalogItemService.findMaxId() == null ? 1
                            : upDataCatalogItemService.findMaxId() + 1;

                    for (MuluzhiliItemVO item : itemList) {
                        UpDataCatalogItem udci = new UpDataCatalogItem();
                        String systemName = item.getSystemName();
                        String scope = item.getScope() == null ? "00" : item.getScope();
                        String systemId = "";

                        if (sysMap.containsKey(systemName + regionCode)) {
                            systemId = sysMap.get(systemName + regionCode);
                        } else {
                            if ("暂无系统".equals(systemName)) {
                                systemId = "000000000000000";
                            } else {
                                String system_region = "";
                                if ("02".equals(scope)) {
                                    system_region = "000000";
                                } else if ("03".equals(scope)) {
                                    system_region = "210000";
                                } else if ("04".equals(scope)) {
                                    system_region = region_code;
                                } else {
                                    system_region = regionCode;
                                }
                                systemId = system_region + scope + item.getBusinessLineCode()
                                        + String.format("%05d", system_id++);

                            }
                            sysMap.put(systemName + regionCode, systemId);
                        }

                        String shareCondition = "数据涉密，不预共享。";
                        if (item.getShareCondition() != null) {
                            String shareConditionStr = item.getShareCondition().trim();
                            if (shareConditionStr.length() > 0) {
                                for (char c : shareConditionStr.toCharArray()) {
                                    if (Character.UnicodeBlock.of(c) == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS) {
                                        shareCondition = shareConditionStr;
                                        break;
                                    }
                                }
                            }
                        }

                        udci.setId(columnMaxId++);
                        udci.setExtCataId(extCataId);
                        udci.setColumnId(UUID.randomUUID().toString());
                        udci.setNameCn(item.getNameCn());
                        udci.setColumnCode(item.getColumnCode());
                        udci.setDataFormat(item.getDataFormat());
                        udci.setShareConditionType(item.getShareConditionType());
                        udci.setShareCondition(shareCondition);
                        udci.setSystemName(systemName);
                        udci.setSystemId(systemId);
                        udci.setSystemGroup(scope);
                        udci.setCreateTime(new Date());
                        udci.setCdTime(new Date());
                        udci.setCdBatch(cdBatch);
                        udci.setStatus(item.getStatus());
                        udci.setExt0(regionCode);

                        upDataCatalogItemService.insert(udci);
                    }
                }
            }

            // 上报统计信息相关
            int reconclition_maxId = upDataReconciliationService.findMaxId() == null ? 1
                    : upDataReconciliationService.findMaxId() + 1;

            if (number > 0) {
                UpDataReconciliation udcr = new UpDataReconciliation();
                udcr.setId(reconclition_maxId++);
                udcr.setRegionCode(region_code);
                udcr.setCdBatch(cdBatch);
                udcr.setCdCount(String.valueOf(number));
                udcr.setTableName("up_data_catalog");
                udcr.setCdTime(new Date());
                udcr.setUpdateTime(new Date());
                upDataReconciliationService.save(udcr);
            }

            if (columnNumber > 0) {
                UpDataReconciliation udcr = new UpDataReconciliation();
                udcr.setId(reconclition_maxId++);
                udcr.setRegionCode(region_code);
                udcr.setCdBatch(cdBatch);
                udcr.setCdCount(String.valueOf(columnNumber));
                udcr.setTableName("up_data_catalog_item");
                udcr.setCdTime(new Date());
                udcr.setUpdateTime(new Date());
                upDataReconciliationService.save(udcr);
            }
        }

        result.put("number", number);
        result.put("columnNumber", columnNumber);
        return result;
    }
}